<!DOCTYPE html>
<html>

<head>
  <title>视频录制示例</title>
  <style>
    body {
      text-align: center;
      /* 让内容居中显示 */
      padding-top: 20px;
      /* 页面顶部留一些空间 */
    }

    .container {
      width: 100%;
      height: 100%;
      --color: #E1E1E1;
      background-color: #F3F3F3;
      background-image: linear-gradient(0deg, transparent 24%, var(--color) 25%, var(--color) 26%, transparent 27%, transparent 74%, var(--color) 75%, var(--color) 76%, transparent 77%, transparent),
        linear-gradient(90deg, transparent 24%, var(--color) 25%, var(--color) 26%, transparent 27%, transparent 74%, var(--color) 75%, var(--color) 76%, transparent 77%, transparent);
      background-size: 55px 55px;
    }

    .card {
      box-sizing: border-box;
      margin: 50px auto;
      width: 600px;
      height: 800px;
      background: rgba(217, 217, 217, 0.58);
      border: 1px solid white;
      box-shadow: 12px 17px 51px rgba(0, 0, 0, 0.22);
      backdrop-filter: blur(6px);
      border-radius: 17px;
      text-align: center;
      cursor: pointer;
      transition: all 0.5s;
      display: flex;
      align-items: center;
      justify-content: center;
      user-select: none;
      font-weight: bolder;
      color: black;
    }

    .card:hover {
      border: 1px solid black;
      transform: scale(1.05);
    }

    .card:active {
      transform: scale(0.95) rotateZ(1.7deg);
    }

    button {
      width: 600px;
      height: 100px;
      color: #090909;
      padding: 0.7em 1.7em;
      font-size: 18px;
      border-radius: 0.5em;
      background: #e8e8e8;
      cursor: pointer;
      border: 1px solid #e8e8e8;
      transition: all 0.3s;
      box-shadow: 6px 6px 12px #c5c5c5, -6px -6px 12px #ffffff;
    }

    button:active {
      color: #666;
      box-shadow: inset 4px 4px 12px #c5c5c5, inset -4px -4px 12px #ffffff;
    }
  </style>
</head>

<body>
  <div class="container">
    <video class="card" id="video" playsinline autoplay></video>
    <button id="startBtn">开始录制</button>
    <!-- <div class="button-container">
        <button id="startBtn">开始录制</button>
        <button id="uploadBtn" disabled>上传视频</button>
      </div> -->
    <div id="countdown"></div>
  </div>

  <!-- ------ -->
  <!-- <input type="file" id="fileInput">
  <button onclick="uploadFile()">上传文件</button> -->
  <!-- ------ -->
  <script type="text/javascript" src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
  <script>
    async function init () {
      const params = new URLSearchParams(window.location.search);
      const signOrderNo = params.get('signOrderNo');
      const dingtalkUserId = params.get('dingtalkUserId');
      // alert(signOrderNo, dingtalkUserId)
      const response = await fetch("https://api.zjcxjc.cn/api/v1/digital-sign/get-compare-result", {
        method: 'POST', // 或 'POST', 根据你的接口要求
        headers: {
          'Content-Type': 'application/json', // 指定发送的数据类型为JSON
        },
        body: JSON.stringify({
          "orderNo": signOrderNo,
          "dingtalkUserId": dingtalkUserId
        })
      });
      const { data, code } = await response.json();
      if (code === 200) {
        // alert(data)
        if (data.res === 'pending' || data.res === 'success') {
          window.location.href = 'https://api.zjcxjc.cn/api/v1/doc/face_success?init=1';
        }
      }
    }
    document.addEventListener('DOMContentLoaded', (event) => {
      init()
    });
    document.getElementById('startBtn').addEventListener('click', function () {
      navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" }, audio: false })
        .then(stream => {
          const video = document.getElementById('video');
          video.srcObject = stream;
          video.play();
          let countdownElement = document.getElementById('countdown');
          let countdown = 5; // 倒计时开始时间
          countdownElement.innerText = `倒计时: ${countdown}秒`;

          // 更新倒计时
          let countdownInterval = setInterval(() => {
            countdown -= 1;
            countdownElement.innerText = `倒计时: ${countdown}秒`;
            if (countdown <= 0) {
              clearInterval(countdownInterval);
              countdownElement.innerText = '录制结束';
            }
          }, 1000);

          // 准备录制
          let mediaRecorder = new MediaRecorder(stream);
          let chunks = [];
          mediaRecorder.ondataavailable = e => chunks.push(e.data);

          // 开始录制
          mediaRecorder.start();

          // 5秒后停止录制
          setTimeout(() => {
            mediaRecorder.stop();
            // 停止摄像头捕获
            stream.getTracks().forEach(track => track.stop());
            video.srcObject = null; // 清除视频源，停止显示视频流
            countdownElement.innerText = ''; // 清空倒计时文本
          }, 5000);

          // 录制停止
          mediaRecorder.onstop = e => {
            const blob = new Blob(chunks, { 'type': 'video/mp4' });
            // 启用上传按钮
            // document.getElementById('uploadBtn').disabled = false;
            const fileName = "recorded-video.mp4"; // 指定文件名
            const fileOptions = { type: blob.type, lastModified: new Date().getTime() }; // 指定文件类型和最后修改时间
            const file = new File([blob], fileName, fileOptions);
            // document.getElementById('res').innerText = `${file}`
            // let res = document.getElementById('res')
            // 上传按钮点击事件
            putObject(file)
            // document.getElementById('uploadBtn').addEventListener('click', async () => {
            //   await putObject(file)
            // }, { once: true }); // 确保事件处理器只触发一次
          };
        })
        .catch(error => {
          console.error('获取摄像头失败:', error);
        });
    });

    async function fetchData () {
      try {
        const response = await fetch("https://api.zjcxjc.cn/api/v1/digital-sign/intention/sign-security-token", {
          method: 'POST', // 或 'POST', 根据你的接口要求
        });
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const { data } = await response.json();
        return data
      } catch (error) {
        console.error('There was a problem with your fetch operation:', error);
      }
    }

    async function putObject (file) {
      const params = new URLSearchParams(window.location.search);
      const signOrderNo = params.get('signOrderNo');
      const dingtalkUserId = params.get('dingtalkUserId');
      // alert(window.location.search)
      try {
        const data = await fetchData(); // 确保这里是异步获取的数据
        if (data) {
          const client = new OSS({
            region: 'oss-cn-hangzhou',
            bucket: "xu-digital-sign",
            accessKeyId: data.AccessKeyId,
            accessKeySecret: data.AccessKeySecret,
            stsToken: data.SecurityToken,
          });
          const date = new Date(); // 获取当前日期
          const year = date.getFullYear(); // 获取四位年份
          const month = date.getMonth() + 1; // 获取月份，需要加1，因为getMonth()返回的月份从0开始计数
          const formattedMonth = month < 10 ? '0' + month : month; // 确保月份是两位数字
          const mp4Url = `sign_order/${year}${formattedMonth}/${signOrderNo}/${dingtalkUserId}.mp4`
          const result = await client.put(mp4Url, file); // 使用 await 等待上传完成
          fetch(`https://api.zjcxjc.cn/api/v1/doc/start_digital_sign?dingtalkUserId=${dingtalkUserId}&orderNo=${signOrderNo}&faceVideoPath=${mp4Url}`, {
            method: 'GET', // 或 'POST', 根据你的接口要求
          });
          window.location.href = `https://api.zjcxjc.cn/api/v1/doc/face_success?init=0&dingtalkUserId=${dingtalkUserId}`;
        } else {
          console.log('Failed to fetch data.');
        }
      } catch (error) {
        console.error('Upload to OSS failed:', error);
      }
    }

    function uploadFile () {
      const fileInput = document.getElementById('fileInput');
      const file = fileInput.files[0];
      if (!file) {
        alert('请先选择一个文件。');
        return;
      }
      putObject(file)
    }
  </script>
</body>

</html>